class ProjectsController < ApplicationController
  layout 'base.html', :only => :index

  def index
    respond_to do |format|
      format.html do
        params[:pay_status] = 'paying'
        projects_by_pay_status
      end
      format.js do
        case
        when params[:pay_status].present?
          projects_by_pay_status
        when params[:project_name].present?
          @projects = Project.find_all_by_name(params[:project_name])
        else
          raise '未知操作'
        end
        render :layout => false
      end
    end
  end
  
  def stat
  end
  
  def new
    @project = Project.new
  end

  def create
    @project = Project.new params[:project]
    render :new unless @project.save
  end
  
  def edit
    @project = Project.find(params[:id])
  end

  def update
    @project = Project.find(params[:id])
    render :edit unless @project.update_attributes(params[:project])
  end

  def destroy
    @project = Project.find(params[:id])
    @project.destroy if @project.stages.empty?
  end

  def print_one
    @project = Project.find(params[:id])
    @html_title = "打印#{@project.name}-提成"
    render :layout => 'base.print'
  end
  
  def title
    @project = Project.find(params[:id])
  end
  
  def show_in_index
    @project = Project.find(params[:id])
  end
  
  def print_many
    projects_by_pay_status
    @html_title = "打印#{t params[:pay_status]}项目提成"
    render :layout => 'base.print'
  end

  private
  def projects_by_pay_status
    case params[:pay_status]
    when 'paying'
      @projects = Project.all(:conditions => 'paying_stages_count > 0')
    when 'paused'
      @projects = Project.all(:conditions => 'paused_stages_count > 0')
    when 'payed'
      @projects = params[:payed_year].present? ? Project.all(:conditions => ['projects.payed_stages_count > 0 and stages.pay_status = ? and strftime("%Y",stages.payed_on) = ? ', 'payed', params[:payed_year]], :include => :stages) : Project.all(:conditions => 'payed_stages_count > 0')
    else
      @projects = Project.all
    end
  end

end

